package com.csii.core.dict.handler;

import cn.hutool.core.collection.CollUtil;
import com.csii.core.constant.SyncDictType;
import com.csii.core.system.vo.SyncDictVo;
import com.csii.galaxy.studio.service.GalaxyStudioBaseService;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RedisDictGetHandler {

    private GalaxyStudioBaseService galaxyStudioBaseService;

    private RedisTemplate redisTemplate;

    private final String IS_DICT_SERVICE_KEY = "IS_DICT_SERVICE";

    private String SYNC_DICT_PREFIX = "SYNC_DICT_PREFIX_";

    private String DICT_SYNC_KEY = "DICT_SYNC_KEY_";

    private int lastSyncResult = 0;

    private boolean isDictService;


    public RedisDictGetHandler(GalaxyStudioBaseService galaxyStudioBaseService, RedisTemplate redisTemplate , String appName ,boolean isDictService) {
        this.galaxyStudioBaseService = galaxyStudioBaseService;
        this.redisTemplate = redisTemplate;
        DICT_SYNC_KEY += appName;
        this.isDictService = isDictService;
        //初始化缓存
        init();
        isDictService();
    }
    private void isDictService(){
        if (isDictService){
            if (redisTemplate != null){
                redisTemplate.opsForValue().set(IS_DICT_SERVICE_KEY,IS_DICT_SERVICE_KEY);
            }
        }
    }

    private void init(){
        if (redisTemplate == null){
            return;
        }

        //判断是不是跟字典主节点在共用redis
        if (redisTemplate.opsForValue().get(IS_DICT_SERVICE_KEY) != null && !isDictService){
            SYNC_DICT_PREFIX = "";
            return;
        }

        //全量同步 增量同步
        SyncDictVo syncDictVo = galaxyStudioBaseService.syncDict(DICT_SYNC_KEY,lastSyncResult);
        //设置上次为失败
        lastSyncResult = -1;
        if (CollUtil.isNotEmpty(syncDictVo.getList())) {
            //增量同步
            redisTemplate.executePipelined(new RedisCallback<SyncDictVo>() {
                @Override
                public SyncDictVo doInRedis(RedisConnection connection) throws DataAccessException {
                    if (SyncDictType.ALL.equals(syncDictVo.getSyncType())) {
                        Set<byte[]> keys = connection.keys((SYNC_DICT_PREFIX + "*").getBytes());
                        for (byte[] key : keys) {
                            connection.del(key);
                        }
                    }

                    syncDictVo.getList().forEach(dict->{
                        if (SyncDictType.OPERATION_SET.equals(dict.getOperationType())){
                            connection.hSet(dict.getDictCode().getBytes(),dict.getItemValue().getBytes(),dict.getItemText().getBytes());
                            connection.expire(dict.getDictCode().getBytes(),86400000);
                        }else {
                            connection.hDel(dict.getDictCode().getBytes(),dict.getItemValue().getBytes());
                        }
                    });
                    return null;
                }
            });
        }
        //到这里就设置上一次请求为成功
        lastSyncResult = 1;
    }


    public String queryDictTextByKey(String code, String key){
        if (redisTemplate != null){
            return (String) redisTemplate.opsForHash().get(code, key);
        }
        return galaxyStudioBaseService.queryDictTextByKey(code,key);
    }


    public void destroy(){
        if (redisTemplate != null){
         redisTemplate.expire(IS_DICT_SERVICE_KEY,3, TimeUnit.HOURS);
        }
    }


}
